<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 通用工具栏组件使用 -->
      <page-tools>
        <!-- 自定义左侧内容 -->
        <template #slot-left>
          <span>共 19 条记录</span>
        </template>

        <!-- 自定义右侧内容 -->
        <template #slot-right>
          <el-button v-power="'import'" type="danger" size="small" @click="uploadBtnFn">导入excel</el-button>
          <el-button v-power="'export'" type="success" size="small" @click="exportBtnFn">导出excel</el-button>
          <el-button type="primary" size="small" @click="addEmpBtnFn">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 员工列表加分页 -->
      <el-card style="margin-top: 10px;">
        <el-table border :data="employeesList">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto" width="120px">
            <template v-slot="{ row }">
              <image-holder :src="row.staffPhoto" class="staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" sortable :sort-method="workNumberSortFn" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template v-slot="scope">
              <span>{{ formatter(scope.row) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" :formatter="timeFormatter" />
          <el-table-column label="操作" width="280">
            <template v-slot="{ row }">
              <el-button type="text" size="small" @click="lookDetailFn(row.id, row.formOfEmployment)">查看</el-button>
              <el-button type="text" size="small" @click="assignRoleBtnFn(row)">分配角色</el-button>
              <el-button type="text" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="end" align="middle" style="height: 60px">
          <!-- 分页区域 -->
          <el-pagination
            :current-page="query.page"
            :page-sizes="[10, 15, 20, 25]"
            :page-size="query.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>

      <!-- 新增员工弹窗 -->
      <el-dialog ref="empForm" title="新增员工" :visible.sync="showDialog" @close="closeFn">
        <emp-form :show.sync="showDialog" :tree-data="treeData" @addEmpEV="addEmpFn" />
      </el-dialog>

      <!-- 员工-分配角色权限 - 弹窗 -->
      <el-dialog title="分配角色" :visible.sync="showRoleDialog">
        <!-- 设置角色组件 -->
        <assign-role-dialog ref="assignRoleDialog" :show.sync="showRoleDialog" :all-role-list="allRoleList" @addRoleEV="addRoleFn" />
      </el-dialog>

    </div>
  </div>
</template>

<script>
import { getEmployeesListAPI, getDepartmentsListAPI, addEmployeesAPI, getRoleListAPI, getUserPhotoAPI, saveEmployeesRoleAPI } from '@/api'
import dayjs from 'dayjs'
import Employees from '@/api/constant'
import EmpForm from './components/empForm.vue'
import assignRoleDialog from './components/assignRoleDialog.vue'
import { transTree } from '@/utils'
export default {
  components: { EmpForm, assignRoleDialog },
  data() {
    return {
      query: {
        page: 1, // 页码
        size: 10 // 每页条数
      },
      employeesList: [], // 员工列表
      total: 0, // 数据总条数
      // hireTypeList: Employees.hireType // 聘用形式
      showDialog: false, // 新增员工显示
      treeData: [], // 部门列表树形结构
      allEmployeesList: [], // 所有员工列表
      showRoleDialog: false, // 分配角色弹窗隐藏
      allRoleList: [], // 所有角色列表
      clickEmpId: '' // 点击分配角色时选中的员工id
    }
  },
  created() {
    // 获取员工列表
    this.getEmployeesListFn()
    // 获取部门列表数据
    this.getDepartmentsListFn()
    // 获取所有角色列表
    this.getRoleListFn()
  },
  methods: {
    // 获取员工列表
    async getEmployeesListFn() {
      const res = await getEmployeesListAPI(this.query)
      console.log(res)
      this.employeesList = res.data.rows
      console.log(this.employeesList)
      this.total = res.data.total
      // 第二次请求，才是为了拿到所有的数据
      const allRes = await getEmployeesListAPI({
        page: 1,
        size: res.data.total // 上一个接口返回后台的总数量
      })
      this.allEmployeesList = allRes.data.rows
      console.log(this.allEmployeesList)
    },
    // 请求部门列表
    async getDepartmentsListFn() {
      const res = await getDepartmentsListAPI()
      this.treeData = transTree(res.data.depts, '')
    },
    // 请求所有角色列表
    async getRoleListFn() {
      const res = await getRoleListAPI({
        page: 1,
        pagesize: 10
      })
      const allRes = await getRoleListAPI({
        page: 1,
        pagesize: res.data.total
      })
      console.log(allRes)
      this.allRoleList = allRes.data.rows
    },
    // 聘用形式
    formatter(row) {
      const obj = Employees.hireType.find(item => item.id === parseInt(row.formOfEmployment))
      return obj ? obj.value : '未知' // obj值为undefined，返回‘未知’
    },
    // 每页显示的条数发生改变时触发
    handleSizeChange(newSize) {
      this.query.size = newSize
      this.getEmployeesListFn()
    },
    // 当前页面发生改变时触发
    handleCurrentChange(newPage) {
      this.query.page = newPage
      this.getEmployeesListFn()
    },
    // 工号-排序方法
    workNumberSortFn(a, b) {
      // console.log(a, b)
      return parseInt(a.workNumber) - parseInt(b.workNumber)
    },
    // 时间格式化
    timeFormatter(row) {
      return dayjs(row.timeOfEntry).format('YYYY-MM-DD')
    },
    // 新增员工按钮的方法
    addEmpBtnFn() {
      this.showDialog = true
    },
    // 新增员工的逻辑请求
    async addEmpFn(empObj) {
      await addEmployeesAPI(empObj)
      this.getEmployeesListFn()
    },
    // 新增员工弹窗关闭事件
    closeFn() {
      this.$refs.empForm.$refs.addForm.resetFields()
    },
    // 点击跳转excel
    uploadBtnFn() {
      this.$router.push('/excel')
    },
    // 导出excel按钮方法
    exportBtnFn() {
      // 类似于懒加载，返回的是promise对象
      import('@/vendor/Export2Excel').then(excel => {
        // 左侧模块内导出的对象
        const tHeader = ['序号', '姓名', '头像', '手机号', '工号', '聘用形式', '部门', '入职时间', '转正时间', '密码', '头像地址']
        // Object.values()->传入对象，返回所有值的数组，取出的值是无序的
        // const newArr = this.employeesList.map(obj => {
        //   return Object.values(obj) // 返回 ['2018-11-30','1','管理员']
        // })
        // console.log(newArr)
        // const data = newArr
        // 1.中文-》英文的对应关系
        const zhAndEnObj = {
        // 序号可以等遍历的时候直接用索引值, 而不是来自于英文对象里
          '姓名': 'username',
          '头像': 'staffPhoto',
          '手机号': 'mobile',
          '工号': 'workNumber',
          '聘用形式': 'formOfEmployment',
          '部门': 'departmentName',
          '入职时间': 'timeOfEntry'
        }
        // 2.遍历每个英文对象
        const data = this.allEmployeesList.map((enObj, index) => {
          // 3.遍历每个中文key
          const newArr = [] // 保存值
          tHeader.forEach(zhKey => {
            if (zhKey === '序号') {
              newArr.push(index + 1)
            } else {
              const enKey = zhAndEnObj[zhKey]
              const value = enObj[enKey]
              if (enKey === 'formOfEmployment') {
                const obj = Employees.hireType.find(item => item.id === parseInt(value))
                newArr.push(obj ? obj.value : '未知')
              } else {
                newArr.push(value)
              }
            }
          })
          // 4.把一行值数组return 给map
          return newArr
        })
        excel.export_json_to_excel({ // 导出excel文件的方法
          // 表格文件的列标题
          header: tHeader,
          data,
          filename: '文件名',
          autoWidth: true, // 单元格自适应
          bookType: 'xlsx' // 文件类型
        })
      })
    },
    // 查看员工详情-点击事件
    lookDetailFn(empId, formOfEmploymentId) {
      this.$router.push(`/employees/detail?id=${empId}&form=${formOfEmploymentId}`)
    },
    // 分配角色弹窗按钮
    async assignRoleBtnFn(empObj) {
      // 根据员工id 换回来员工详细信息
      const res = await getUserPhotoAPI(empObj.id)
      console.log(res)
      this.clickEmpId = empObj.id
      this.showRoleDialog = true
      this.$nextTick(() => {
        this.$refs.assignRoleDialog.roleIdsList = res.data.roleIds
      })
      // 等异步DOM更新完毕后，vue会回调（）里函数体执行
    },
    // 保存角色
    async addRoleFn(roleIdsList) {
      const res = await saveEmployeesRoleAPI({
        id: this.clickEmpId,
        roleIds: roleIdsList
      })
      console.log(res)
    }
  }
}
</script>
<style lang="scss" scoped>
.staffPhoto {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}
</style>
